<?php
/**
 * Enter description here...
 *
 * @package if
 * @subpackage module.helper.controllers
 * @since 1.0
 */
class IfHelperConfigMessageController extends IHelperController {
	function _init() {
		$this->opts = o("@locale");
		$this->names = array();
		foreach ($this->opts as $key => $opt) {
			if (is_array($opt) && isset($opt["message"]) && $key != "tpl") {
				$this->names[] = $key;
			}
		}
		$this->file = IApplication::singleton()->directory("config") . "/_locale.php";
	}
	
	function doIndex() {
		if ($this->form("global")->isValid()) {
			$config = new IConfig($this->file);
			$config->set("default_name", $this->names[x("name")]);
			$config->write();
			if_clean_compiler_dir();
			$this->redirect("index");			
		}
		
		if ($this->form("new")->isValid()) {
			$config = new IConfig($this->file);
			$config->set(x("name"), xn("opt"));
			$config->write();
			if_clean_compiler_dir();
			$this->redirect("index");
		}
	}
	
	function doLocale() {
		$name = x("name");
		$this->opt = $this->opts[$name];
		
		$locale = new ILocale($name);
		$messages = $locale->messages();
		
		$this->messages = $this->_arrayToDot($messages);
		ksort($this->messages);

		if ($this->form("config")->isValid()) {
			$config = new IConfig($this->file);
			$config->set($name, x("opt"));
			$config->write();
			if_clean_compiler_dir();
			$this->redirect("locale", null, array( "name" => $name ));
		}
		
		if ($this->form("message")->isValid()) {
			$this->_save($name, xn("message"));
		}
		
		if ($this->form("new")->isValid()) {
			$this->messages[xn("key")] = xn("message");
			$this->_save($name, $this->messages);
		}
	}
	
	function doDelete() {
		$name = x("name");
		$locale = new ILocale($name);
		$messages = $locale->messages();
		$messages = $this->_arrayToDot($messages);
		unset($messages[xn("key")]);
		ksort($messages);
		
		$this->_save($name, $messages);
	}
	
	private function _arrayToDot($array) {
		$ret = array();
		foreach ($array as $key => $value) {
			if (is_array($value)) {
				foreach ($this->_arrayToDot($value) as $k => $v) {
					$ret[$key . "." . $k] = $v;
				}
			}
			else {
				$ret[$key] = $value;
			}
		}
		return $ret;
	}
	
	private function _save($name, $messages) {
		//保存
		$file = IApplication::singleton()->directory("config") . "/locale/{$name}/_message.php";
		if (is_array($messages)) {
			$string = "<?php\n\$message=" . var_export($messages, true) . ";\n?>";
			f($file)->writer()->write($string, true);
		}
		if_clean_compiler_dir();
		$this->redirect("locale", null, array( "name" => $name ));
	}
}

?>